package main

import (
	"crypto/tls"
	"crypto/x509"
	"fmt"
	"io/ioutil"
	"net/http"
)

func main() {
	//1.读取服务器颁发的证书ca内容
	caCerInfo, err := ioutil.ReadFile("./14单项认证/cert.crt")
	if err != nil {
		fmt.Println("1err", err)
		return
	}
	//2. 创建ca池，
	CertPool := x509.NewCertPool()
	//将内容加入到ca池中
	ok := CertPool.AppendCertsFromPEM(caCerInfo)
	fmt.Println("ok=", ok)

	//加载客户端的ca证书
	clientCert,err:=tls.LoadX509KeyPair("./15-双向认证/client.crt","./15-双向认证/client.key")
	if err != nil {
		fmt.Println("2err", err)
		return
	}

	//2.配置tls
	cfg:=tls.Config{
		RootCAs: CertPool,
		// 客户端证书
		Certificates: []tls.Certificate{clientCert},
	}
	
	client:=http.Client{
		Transport: &http.Transport{
			TLSClientConfig: &cfg,
		},
	}
	//发起请求
	resp, err := client.Get(`https://localhost:9090/test1`)
	if err != nil {
		fmt.Println("2err:", err)
		return
	}
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println("1err", err)
		return
	}
	defer func() {
		fmt.Println("结束main运行")
		defer resp.Body.Close()
	}()
	if err != nil {
		fmt.Printf("read from resp.Body failed, err:%v\n", err)
		return
	}
	fmt.Println("body：",string(body))
	fmt.Println("status code：",resp.Status)
}